package com.ibm.crl.sb.thread.czbk;

import java.util.Random;

/**
 * 
 * @author Super尚
 * 
 *         与当前线程相关的书据
 */
public class ThreadLocalDemo {

	private ThreadLocal<Integer> threadData = new ThreadLocal<Integer>();

	// private ThreadLocal<MyThreadScopeData> myThreadScopeData = new
	// ThreadLocal<MyThreadScopeData>();

	public ThreadLocalDemo() {
		for (int i = 0; i < 2; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					int data = new Random().nextInt();
					System.out.println(Thread.currentThread().getName()
							+ "has put data" + data);
					threadData.set(data);
					MyThreadScopeData myData = MyThreadScopeData.getInstance();
					myData.setName("");
					myData.setAge(0);
					new A().getData();
					new B().getData();
				}

			}).start();
		}
	}

	public static void main(String[] args) {
		new ThreadLocalDemo();
	}

	class A {

		public void getData() {
			int data = threadData.get();
			System.out.println(Thread.currentThread().getName() + "A get data"
					+ data);
		}

	}

	class B {
		public void getData() {
			int data = threadData.get();
			System.out.println(Thread.currentThread().getName() + "B get data"
					+ data);
		}

	}
}

class MyThreadScopeData {

	private MyThreadScopeData() {

	}

	// private static MyThreadScopeData instance = null;// new
	private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();

	// MyThreadScopeData();

	// public static synchronized MyThreadScopeData getInstance() {
	// synchronized 精髓
	// if (instance == null) {
	// instance = new MyThreadScopeData();
	// }
	// return instance;
	// }

	public static MyThreadScopeData getInstance() {
		MyThreadScopeData instance = map.get();
		if (instance == null) {
			instance = new MyThreadScopeData();
			map.set(instance);
		}
		return instance;
	}

	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}
